package utility.alarm;

import java.util.Vector;

import object.alarm.Calculation;

public class MathRandom {
	private final static MathRandom mrd = new MathRandom();
	public static MathRandom getInstance(){
		return mrd;
	}
	
	private static int OPTION_RD_ListSize = 1;
	private static int OPTION_RD_Number = 2;
	private static int OPTION_RD_Operation = 3;
	
	public final static int OPERATION_PLUS = 1;
	public final static int OPERATION_SUB = 2;
	public final static int OPERATION_MULTI = 3;
	public final static int OPERATION_DIV = 4;
	
	private int minMath = 1;
	private int maxMath = 3;
	private int minNum = 0;
	private int maxNum = 1000;
	private int minOperation = 1;
	private int maxOperation = 4;
	
	private int totalMath;
	
	private int random(int option){
		int re = 0;
		if(option == OPTION_RD_ListSize) {
			re =  minMath+ (int)(Math.random()*(maxMath-minMath+1));
		}else if(option == OPTION_RD_Number){
			re = minNum + (int)(Math.random()*(maxNum-minNum+1));
		}else if(option == OPTION_RD_Operation){
			re = minOperation + (int)(Math.random()*(maxOperation-minOperation+1));
		}
		return re;
	}
	
	private int cal(int num1, int num2, int operation){
		int result=0;
		if(operation == OPERATION_PLUS) {
			result = num1+num2;
			if(result>1000){
				return -1;
			}
		}else if(operation == OPERATION_SUB){
			result = num1-num2;
			if(result<0){
				return -1;
			}
		}else if(operation == OPERATION_MULTI){
			result = num1*num2;
			if(result>1000){
				return -1;
			}
		}else if(operation == OPERATION_DIV){
			result = num1/num2;
			if(result<1 || (num1%num2!=0 && result>=1)){
				return -1;
			}
		}
		return result;
	}
	
	private Calculation initNewMath(){
		int num1;
		int num2;
		int opre;
		int result;
		while (true) {
			num1 = random(OPTION_RD_Number);
			num2 = random(OPTION_RD_Number);
			opre = random(OPTION_RD_Operation);
			result = cal(num1, num2, opre);
			if(result!=-1) break;
		}
		Calculation cal = new Calculation();
		cal.setNum1(num1);
		cal.setNum2(num2);
		cal.setOperation(opre);
		cal.setResult(result);
		return cal;
	}
	
	public Vector<Calculation> init(){
		Vector<Calculation> listCal = new Vector<Calculation>();
		totalMath = random(OPTION_RD_ListSize);
		for(int i=0; i<mrd.totalMath;i++){
			Calculation a = mrd.initNewMath();
			listCal.add(a);
		}
		return listCal;
	}	
}
